#!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
@Author   : long.hai
@Contact  : 1982964634@qq.com
"""
import json
import time
import traceback
from _base.base import BasePage
from _step.drive_page import DrivePage
from _step.logic import Logic
from _step.step import StepList, Step
from utils.common import now


class BaseStep(DrivePage, Logic):

    def __init__(self, base_page):
        self.base_page: BasePage = base_page
        DrivePage.__init__(self, base_page)
        Logic.__init__(self, base_page)

    # 单步骤执行
    async def single_step(self, step: Step):
        try:
            method = step.action.method
            if method == 'if_control':
                await self.if_control(step)
            else:
                await self.before(step)
        except Exception as e:
            error = str(e)
            await self.base_page.log_error(error)
            server_error = {"code": 500, "uuid": step.uuid, "msg": error}
            await self.custom(json.dumps(server_error))

    async def multiple_step(self, steps: StepList):
        """
        递归执行测试用例步骤
        :param steps: 测试步骤列表
        """
        # 判断是否需要监听接口数据
        # my_playwright.extract_state = True
        # my_playwright.extract_path = 'generateCertificateCode'

        uuid = None
        for step in steps.children:
            try:
                uuid = step.uuid
                # 判断步骤是否启用
                if self.is_enable(step.enable):
                    await self.base_page.collect_step_report(step.name, 4, 0)
                    continue

                # 判断步骤执行前等待时间
                await self.before_wait(step.config.before_wait)

                # 判断是否开启智能等待页面加载稳定后执行
                await self.intelligence_wait(step.config.intelligence_wait)

                # 判断步骤是否为特殊逻辑处理：条件控制（if_control）
                method = step.action.method
                if method == 'if_control':
                    await self.send_rate(uuid, 20, )
                    if hasattr(step, "children") and len(step.children) > 0:
                        conditions = self.base_page.re_replace_variable(step.params)
                        if_result = await self.multiple_if_control(conditions)
                        await self.base_page.log_info(f"判断结果: {if_result}")
                        await self.send_rate(uuid, 100)
                        if if_result:
                            await self.multiple_step(step)
                    else:
                        await self.send_rate(uuid, 100)

                # 判断步骤是否为特殊逻辑处理：调用流程/用例（call_process）
                elif method == 'call_process':
                    await self.send_rate(uuid, 100)
                    await self.multiple_step(step)

                # 普通页面操作直接执行
                else:
                    # 执行页面操作
                    await self.before(step)
            # 处理异常
            except Exception as e:
                # traceback.print_exc()
                # 发送执行错误异常信息
                server_error = {"code": 500, "uuid": uuid, "msg": f'执行失败: {str(e)}'}
                await self.custom(json.dumps(server_error))
                # 判断步骤是否开启异常继续执行
                if self.ignore_error(step.config.ignore_error):
                    continue
                else:
                    raise e

    async def if_control(self, step: Step):
        await self.send_rate(step.uuid, 20)
        conditions = self.base_page.re_replace_variable(step.params)
        if_result = await self.multiple_if_control(conditions)
        await self.send_rate(step.uuid, 100)
        if not if_result:
            error = '判断未通过。%s' % (json.dumps(conditions, indent=4),)
            await self.base_page.log_error(error)
            raise ValueError(error)
